import type { LocaleSetupOptions, SupportedLanguagesType } from '@vben/locales'
import type { Locale } from 'ant-design-vue/es/locale'

import type { App } from 'vue'
import { ref } from 'vue'

import { $t, setupI18n as coreSetup, loadLocalesMapFromDir } from '@vben/locales'
import { preferences } from '@vben/preferences'

import DictionaryApi from '#/api/system/dictionary'
import { LocaleDictionaryPrefix } from '#/config'
import { CountryLanguageOptions } from '#/config/options/locales'
import { getOptionsLabelByValue } from '#/config/options/utils'
import { rebuildZStructure } from '#/utils/localesConfig'
import antdEnLocale from 'ant-design-vue/es/locale/en_US'
import antdDefaultLocale from 'ant-design-vue/es/locale/zh_CN'
import dayjs from 'dayjs'

const antdLocale = ref<Locale>(antdDefaultLocale)

const modules = import.meta.glob('./langs/**/*.json')

export const localesMap = loadLocalesMapFromDir(/\.\/langs\/([^/]+)\/(.*)\.json$/, modules)

/**
 * 字典中获取语言包
 */
async function getLocaleMessagesByDictionary(lang?: SupportedLanguagesType) {
    const langVal = getOptionsLabelByValue(lang, CountryLanguageOptions)

    console.log(langVal)
    const arr = ((await DictionaryApi.inst.getI18nAll()) || []).map((v: any) => {
        const name = v.itemList.find((v2: any) => v2.code === langVal)?.name
        return {
            ...v,
            name,
            // 本地没有前缀
            code: v.code.replace(new RegExp(`^${LocaleDictionaryPrefix}`), '')
        }
    })

    const defaultArr = rebuildZStructure(arr, {
        labelKey: 'name',
        valueKey: 'code'
    })

    // console.log(defaultArr, arr, '远程语言配置')

    return {
        default: defaultArr
    }
}

/**
 * 加载应用特有的语言包
 * 这里也可以改造为从服务端获取翻译数据
 * @param lang
 */
async function loadMessages(lang: SupportedLanguagesType) {
    await new Promise((r) => setTimeout(r, 1000))
    const [appLocaleMessages] = await Promise.all([
        // localesMap[lang]?.(),
        getLocaleMessagesByDictionary(lang),
        loadThirdPartyMessage(lang)
    ])

    return appLocaleMessages?.default
}

/**
 * 加载第三方组件库的语言包
 * @param lang
 */
async function loadThirdPartyMessage(lang: SupportedLanguagesType) {
    await Promise.all([loadAntdLocale(lang), loadDayjsLocale(lang)])
}

/**
 * 加载dayjs的语言包
 * @param lang
 */
async function loadDayjsLocale(lang: SupportedLanguagesType) {
    let locale
    switch (lang) {
        case 'en-US': {
            locale = await import('dayjs/locale/en')
            break
        }
        case 'zh-CN': {
            locale = await import('dayjs/locale/zh-cn')
            break
        }
        // 默认使用英语
        default: {
            locale = await import('dayjs/locale/en')
        }
    }
    if (locale) {
        dayjs.locale(locale)
    } else {
        console.error(`Failed to load dayjs locale for ${lang}`)
    }
}

/**
 * 加载antd的语言包
 * @param lang
 */
async function loadAntdLocale(lang: SupportedLanguagesType) {
    switch (lang) {
        case 'en-US': {
            antdLocale.value = antdEnLocale
            break
        }
        case 'zh-CN': {
            antdLocale.value = antdDefaultLocale
            break
        }
    }
}

async function setupI18n(app: App, options: LocaleSetupOptions = {}) {
    await coreSetup(app, {
        defaultLocale: preferences.app.locale,
        loadMessages,
        missingWarn: !import.meta.env.PROD,
        ...options
    })
}

export { $t, antdLocale, setupI18n }
